import extend from 'dva-model-extend';
// import settings from '@/settings';
import model from '@/baseModel';
import { getOne, getNode, deleteRows, deleteNode, getNodes, getList } from '@/services/dictionary';

// const { pagination } = settings;

const initState = {
  nodes: []
}

export default extend(model, {
  namespace: 'dictionary',
  state: {
    ...initState
  },
  effects: {
    *reset(_, { put }) {
      yield put({
        type: 'updateState',
        payload: {
          data: undefined
        },
      });
    },
    *resetNode(_, { put }) {
      yield put({
        type: 'updateState',
        payload: {
          node: []
        },
      });
    },
    *resetNodes(_, { put }) {
      yield put({
        type: 'updateState',
        payload: {
          nodes: []
        },
      });
    },
    *fetchOne({ payload = {} }, { call, put }) {
      const {
        id
      } = payload
      const { data = {} } = yield call(getOne, payload);
      yield put({
        type: 'updateState',
        payload: {
          data: (data.prop || []).filter(_ => _.name === id)[0]
        },
      });
    },
    *fetchNode({ payload }, { call, put }) {
      const { data } = yield call(getNode, payload);
      yield put({
        type: 'updateState',
        payload: {
          node: data
        },
      });
    },
    *deleteNode({ payload }, { call, put }) {
      yield call(deleteNode, payload);
      yield put({
        type: 'fetchNodes'
      });
    },
    *fetchNodes({ payload }, { call, put }) {
      const { data } = yield call(getNodes, payload);
      yield put({
        type: 'updateState',
        payload: {
          nodes: data
        },
      });
    },
    *delete({ payload }, { call, put }) {
      yield call(deleteRows, payload);
    },
    // *fetchList({ payload = pagination }, { call, put }) {
    //   const { data } = yield call(getList, payload);
    //   yield put({
    //     type: 'updateState',
    //     payload: {
    //       list: data,
    //       params: payload,
    //     },
    //   });
    // },
    *fetchList({ payload = {} }, { call, put }) {
      const {
        name
      } = payload
      const { data } = yield call(getList, payload);

      yield put({
        type: 'updateState',
        payload: {
          list: name ? data.filter(_ => _.name.indexOf(name) > -1) : data,
        },
      });
    }
  },
});
